package com.boat.starter.ruoyi.listener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import com.boat.starter.ruoyi.client.RedisClient;
import com.boat.starter.ruoyi.client.RuoyiClient;
import com.boat.starter.ruoyi.client.response.RmsResponse;
import com.boat.starter.ruoyi.client.response.SyncConfigResp;
import com.boat.starter.ruoyi.config.props.AuthProperties;

import lombok.extern.slf4j.Slf4j;

/**
 * 同步配置监听器
 * @author 周江
 *
 */
@Slf4j
public class SyncConfigRunner implements ApplicationRunner {
	private AuthProperties authProperties;
	
	@Autowired
	private RuoyiClient rmsClient;
	@Autowired
	private RedisClient redisClient;
	
	public SyncConfigRunner(AuthProperties authProperties){
		this.authProperties = authProperties;
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {

		RmsResponse<SyncConfigResp> rmsResponse = rmsClient.syncConfig();
		if(!rmsResponse.isSuccess()) {
			throw new RuntimeException("同步rms配置出错，请检查！");
		}
		
		SyncConfigResp syncConfigResp = rmsResponse.getData();
		this.authProperties.getRuoyi().getRedis().setDatabase(syncConfigResp.getDatabase());
		this.authProperties.getRuoyi().getRedis().setHost(syncConfigResp.getHost());
		this.authProperties.getRuoyi().getRedis().setPassword(syncConfigResp.getPassword());
		this.authProperties.getRuoyi().getRedis().setPort(syncConfigResp.getPort());
		this.authProperties.getRuoyi().getToken().setSecret(syncConfigResp.getSecret());
		redisClient.init();
	}

}
